﻿using System;
using System.Data;
using System.Net;
using System.Web;
using SplendidCRM;

namespace Netpower.TheWall.Web.Desktop
{
	public class ShowFile : IHttpHandler
	{

		#region IHttpHandler Members
				
		///<summary>
		///Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"></see> interface.
		///</summary>
		///
		///<param name="context">An <see cref="T:System.Web.HttpContext"></see> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests. </param>
		public void ProcessRequest(HttpContext context)
		{
			Guid importId = GetImportId(context);
			ConfigureCaching(context);
            ReturnFile(context, importId);
		}

		///<summary>
		///Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"></see> instance.
		///</summary>
		///
		///<returns>
		///true if the <see cref="T:System.Web.IHttpHandler"></see> instance is reusable; otherwise, false.
		///</returns>
		///
		public bool IsReusable
		{
			get { return true; }
		}

		#endregion

		private void ConfigureCaching(HttpContext context)
		{
			context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
			context.Response.Cache.SetNoStore();
			context.Response.Cache.SetExpires(DateTime.MinValue);
		}

		private void ReturnFile(HttpContext context, Guid importId)
		{
		    var binary = GetByteArrayByImportId(importId);
            if (binary == null)
            {
                ReturnFileNotFound(context);
                return;
            }

            context.Response.ContentType = "application/vnd.ms-excel";
			context.Response.ContentEncoding = System.Text.Encoding.UTF8;
			context.Response.AddHeader("content-disposition", "attachment; filename=" + "ImportedData.xls");
			context.Response.BinaryWrite(binary);
		}

        private byte[] GetByteArrayByImportId(Guid importId)
        {
            var dbf = DbProviderFactories.GetFactory();
            using (IDbConnection con = dbf.CreateConnection())
            {
                con.Open();
                var cmdSelectImportedList = con.CreateCommand();
                cmdSelectImportedList.CommandType = CommandType.Text;
                cmdSelectImportedList.CommandText =
@"select * from IMPORTS where IMPORT_ID = @IMPORT_ID";
                Sql.AddParameter(cmdSelectImportedList, "@IMPORT_ID", importId);
                IDbDataAdapter da = dbf.CreateDataAdapter();
                da.SelectCommand = cmdSelectImportedList;
                var ds = new DataSet();
                da.Fill(ds);
                var data = ds.Tables[0];
                con.Close();
                return data != null && data.Rows.Count > 0 ? data.Rows[0]["IMPORT_DATA"] as byte[] : null;
            }
        }

		private void ReturnFileNotFound(HttpContext context)
		{
			context.Response.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
			context.Response.End();
		}

		/// <summary>
		/// Gets the IMPORT_ID from the QueryString
		/// </summary>
		/// <param name="context"></param>
		/// <returns></returns>
		private Guid GetImportId(HttpContext context)
		{
			string variable = context.Request.QueryString["IMPORT_ID"];
			if(string.IsNullOrEmpty(variable))
			{
				return Guid.Empty;
			}
			return Sql.ToGuid(variable);
		}
	}
}
